package com.tianqu.tms.core.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
public class TempletUtil {
     
    public static final String DEFAULT_SPLIT = "#";
     
    public static void main(String[] args) {
        Map<String, String> context = new HashMap<String, String>();
        context.put("value", "1fff");
        String render = render("aaaa#value#bbbbb", context );
        System.out.println(render);
    }
     
    public static String render(String templet, Map<String, String> context) {
        return render(templet, DEFAULT_SPLIT, context);
    }
     
    public static String render(String templet, String split, Map<String, String> context) {
        Set<String> paramNames = getParamNames(templet, split);
 
        for (String name : paramNames) {
            String value = context.get(name);
            value = value == null ? "" : value;
            String regex = "\\Q" + split + name + split + "\\E";
            templet = templet.replaceAll(regex, value);
        }
 
        return templet;
    }
     
    public static Set<String> getParamNames(String templet, String split) {
        Set<String> paramNames = new HashSet<String>();
         
        int start = 0, end = 0;
        while (end < templet.length()) {
            start = templet.indexOf(split, end) + split.length();
            if (start == -1) {
                break;
            }
            end = templet.indexOf(split, start);
            if (end == -1) {
                break;
            }
            paramNames.add(templet.substring(start, end));
            end = end + split.length();
        }
        return paramNames;
    }
     
}
